package com.arpa.wms.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.arpa.core.web.MediaTypes;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.cache.ShipmentCache;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.util.ShipmentWarehouseValidate;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.domain.enums.CustomerCheckStatusEnum;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.wms.domain.consts.CommonConst;
import com.arpa.wms.domain.consts.PropertyConst;
import com.arpa.wms.domain.consts.TipConst;
import com.arpa.wms.domain.dto.BrandDTO;
import com.arpa.wms.domain.entity.Brand;
import com.arpa.wms.domain.entity.Container;
import com.arpa.wms.domain.enums.StatusEnum;
import com.arpa.wms.domain.vo.BrandVO;
import com.arpa.wms.service.IBrandService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 品牌 Controller
 * </p>
 *
 * @author LEO
 * @since 2020-08-03
 */
@Api(tags = "品牌")
@RestController
@RequestMapping(value="/brand", produces = "application/json;charset=UTF-8")
@Log4j2
public class BrandController   {

   @Autowired
   private IBrandService  iBrandService;

    /**
     * 获取 品牌 列表
     *
     * @param brandDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 品牌 列表", notes = "获取 品牌 列表")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = BrandVO.class))
    @NeedLogin
    @GetMapping
    public Result list(BrandDTO brandDTO,HttpServletRequest request) {
        try {
            //校验授权仓库code和货主code不能为空
            Map<String, List<String>> authMap = ShipmentWarehouseValidate.validateShipmentCodesAndWarehouseCodes();
            //登录仓库授权的货主过滤
            brandDTO.setShipmentCodes(authMap.get(CommonConst.SHIPMENT_CODES));
            //所属机构的过滤条件
            brandDTO.setGroupCode(UserUtil.getBranchCode());
            BrandVO brandVos = iBrandService.queryListSum(brandDTO);
            List<BrandVO> brandVOList = iBrandService.queryList(brandDTO);

            Page returnPage = new Page(brandDTO.getPageNum(),brandDTO.getPageSize());
            returnPage.setRecords(brandVOList);
            returnPage.setTotal(brandVos.getTotal());
            returnPage.setSumObject(brandVos);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 添加 品牌
     *
     * @param entity Brand
     * @param request
     * @return
     */
    @ApiOperation(value = "添加 品牌 ", notes = "添加 品牌 ")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PostMapping
    public Result create(Brand entity, HttpServletRequest request) {
        entity.setGroupCode(UserUtil.getBranchCode());
        try {
            iBrandService.save(entity);
            return Result.ok("添加成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
    * 获取品牌详情
    *
    * @param code
    * @param request
    * @return
    */
    @ApiOperation(value = "获取品牌详情", notes = "获取品牌详情")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
        @ApiImplicitParam(name = "code", value = "品牌code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = BrandVO.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result detail(@PathVariable String code, HttpServletRequest request) {
        try {
            Brand entity = iBrandService.getOne(new QueryWrapper<Brand>().lambda().eq(Brand::getCode,code).eq(Brand::getGroupCode,UserUtil.getBranchCode()));
            return Result.ok().data(entity);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }



    /**
     * 修改品牌
     * @param entity 品牌
     * @param request
     * @return
     */
    @ApiOperation(value = "修改品牌", notes = "修改品牌")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping
    public Result update(Brand entity,HttpServletRequest request) {

        try{
            if(StrUtil.isBlank(entity.getCode())){
                return Result.error(TipConst.CODE_NOT_EMPTY);
            }
            int updateNum = iBrandService.updateByCode(entity);
            if(updateNum == 0){
                return Result.error("没有更新数据！code:"+entity.getCode());
            }else{
                return Result.ok("修改成功,更新"+updateNum+"条数据！");
            }
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 品牌停用
     *
     * @param codes 品牌code
     * @param request
     * @return
     */
    @ApiOperation(value = "品牌停用", notes = "品牌停用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
    })
    @NeedLogin
    @PutMapping(value = "/unactive")
    public Result unactive(@RequestParam List<String> codes,HttpServletRequest request) {
        if(IterUtil.isEmpty(codes)){
            return Result.error(TipConst.CODE_NOT_EMPTY);
        }
        Map<String, Object> result = iBrandService.batchUpdateStatus(codes, StatusEnum.UNACTIVE.getValue());
        Integer success = MapUtil.getInt(result, PropertyConst.SUCCESS);
        List<String> useName = MapUtil.get(result, "useName", List.class);
        int failNum = codes.size() - success;
        StringBuilder builder = new StringBuilder();
        builder.append("停用成功" + success + "条；失败" + failNum + "条；");
        if(IterUtil.isNotEmpty(useName)){
            for (String m:useName) {
                builder.append("<br><font color='red'>品牌【"+m+"】停用失败，商品正在使用中;</font>");
            }
        }
        return Result.ok(builder.toString());
    }

    /**
     * 品牌启用
     *
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "品牌启用", notes = "品牌启用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "codes", value = "codes", required = true, paramType = "query", dataType = "List")
    })
    @NeedLogin
    @PutMapping(value = "/active")
    public Result active(@RequestParam  List<String> codes,HttpServletRequest request) {
        if(IterUtil.isEmpty(codes)){
            return Result.error(TipConst.CODE_NOT_EMPTY);
        }
        Map<String, Object> result = iBrandService.batchUpdateStatus(codes, StatusEnum.ACTIVE.getValue());
        Integer success = MapUtil.getInt(result, PropertyConst.SUCCESS);
        int failNum = codes.size() - success;
        return Result.ok("启用成功" + success + "条；失败" + failNum + "条；");
    }


    @ApiOperation(value = "删除品牌信息", notes = "删除品牌信息", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "codes", value = "品牌code", paramType = "path", dataType = "String")
    })
    @NeedLogin
    @DeleteMapping(value = "/{codes}")
    public Result delete(@PathVariable List<String> codes, HttpServletRequest request) {

        try {
            Map<String, Object> result = iBrandService.removeByCode(codes);
            Integer success = MapUtil.getInt(result, PropertyConst.SUCCESS);
            List<String> notDelete = MapUtil.get(result, "notDelete", List.class);
            int failNum = codes.size() - success;
            StringBuilder buffer = new StringBuilder();
            buffer.append("删除成功").append(success).append("条；失败").append(failNum).append("条；");
            if(IterUtil.isNotEmpty(notDelete)){
                for (String m:notDelete) {
                    buffer.append("<br><font color='red'>品牌【").append(m).append("】删除失败，已被启用过;</font>");
                }
            }
            return Result.ok(buffer.toString());
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }



    @ApiOperation(value = "获取货主商品品牌列表", notes = "获取货主商品品牌列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @GetMapping(value = "/findByShipmentCode")
    public Result findByShipmentCode(String shipmentCode, HttpServletRequest request) {
        try {
            List<Map<String, Object>> brands = iBrandService.findByShipmentCode(shipmentCode);
            return Result.ok().data(brands);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


}
